const express = require("express");
const fs = require("fs");
const path = require("path");
const baseUrl = require("../../common/baseUrl");
const { v4: uuidv4 } = require("uuid");

// 创建路由容器
const router = express.Router();
const { isArrayFn } = require("../../common/methods");

const db = require("../../db");

// 上传文件
router.post("/upload", function (req, res) {
  let avatar = req.files.avatar;
  const filePath = req.body.filePath; // 前端传过来的存储路径
  const contents = `static/${filePath ? filePath : ""}`; // 文件存储路径
  const filesArr = [];
  if (isArrayFn(avatar)) {
    // 多文件上传
    for (let i = 0; i < avatar.length; i++) {
      avatar[i].name = uuidv4() + "-" + avatar[i].name; // 修改文件名称 避免重复
      filesArr.push({
        url: baseUrl + "/" + contents + avatar[i].name,
      });
      avatar[i].mv(`${contents}${avatar[i].name}`, (err) => {
        if (err) return res.status(500).send(err);
      });
    }
    res.json({
      status: 0,
      msg: "File uploaded!",
      data: filesArr,
    });
  } else {
    // 单文件上传
    avatar.name = uuidv4() + "-" + avatar.name; // 修改文件名称 避免重复
    avatar.mv(`${contents}${avatar.name}`, function (err) {
      if (err) return res.status(500).send(err);
      return res.json({
        status: 0,
        msg: "File uploaded!",
        data: {
          url: baseUrl + "/" + contents + avatar.name,
        },
      });
    });
  }
});

module.exports = router;
